package cirno.open.api.listener;

import cirno.open.api.config.EmailConfig;
import cn.hutool.core.util.RandomUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.util.concurrent.TimeUnit;

import static cirno.open.api.constant.EmailConstant.*;
import static cirno.open.api.constant.EmailConstant.EMAIL_TITLE;
import static cirno.open.api.utils.EmailUtil.buildEmailContent;

@Component
@RequiredArgsConstructor
public class MailListener {

    private final StringRedisTemplate redisTemplate;

    private final JavaMailSender mailSender;

    private final EmailConfig emailConfig;

    @RabbitListener(
            bindings = @QueueBinding(
                    key = {"user.email.captcha"},
                    value = @Queue("cirno"),
                    exchange = @Exchange(name = "cirno.direct", type = ExchangeTypes.DIRECT)))
    public void listenAndSendEmail(String emailAccount) throws MessagingException {
        //生成验证码
        String captcha = RandomUtil.randomNumbers(6);
        // 邮箱发送内容组成
        MimeMessage message = mailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(message, true);
        helper.setSubject(EMAIL_SUBJECT);
        helper.setText(buildEmailContent(EMAIL_HTML_CONTENT_PATH, captcha), true);
        helper.setTo(emailAccount);
        helper.setFrom(EMAIL_TITLE + '<' + emailConfig.getEmailFrom() + '>');
        //发送邮件
        mailSender.send(message);
        //将验证码保存到redis以便于与用户核对
        redisTemplate.opsForValue().set(CAPTCHA_CACHE_KEY + emailAccount, captcha, 5, TimeUnit.MINUTES);
    }
}
